/**
 * Pool management
 */

var pool = {
	/**
	 * Show pool list
	 */
	list : function() {
		// Request pool list url from poolController.
		var poolListUrl = baseURL + "/cluster/pool"
		$.ajax({
			type : "get",
			url : poolListUrl,
			dataType : "html",
			success : function(html) {
				// Request successfully and fill the data.
				$("#list").empty().html(html);
			}
		});
	},

	/**
	 * Create new pool
	 */
	create : function() {
		common.dialog({
			obj : "#createPoolDialog",
			url : baseURL + "/cluster/pool/create",
			title : localeMsg.pool.create,
			width : 600,
			heigth : 300,
			confirm : function() {
				var data = $("#createPoolForm").form('validate');
				if (data == true) {
					pool.createsave();
				} else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.invalidData,
						success : false
					});
				}
			}
		});
	},

	/**
	 * CreateSave pool
	 */
	createsave : function() {
		$("#createPoolForm").ajaxSubmit({
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.prompt,
						text : localeMsg.common.buildSuccess,
						callback : function() {
							//pool.list();
							location.reload();
						},
						success : true
					});
				} else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.buildFailed,
						success : false
					});
				}
			}
		});
	},
	/**
	 * get poolname
	 */
	poolmessage : function(e){
		this.value =  $(e).find("span[target]").text();
		var value = $(e).find("span[target]").text();
		},
	/**
	 * Modify pool
	 */
	modify : function() {
		// Get the first poolName from checked buttons
		var poolName = this.value;
		if (poolName == undefined) {
			common.showTip({
				title : localeMsg.common.warn,
				text : localeMsg.common.selectMsg,
				success: false
			});
		} else {
			/*String.prototype.trim = function()  
			{  
			return this.replace(/(^\s*)|(\s*$)/g, "");  
			} */
			poolName = $.trim(this.value);
			var param = {
				poolName : poolName
			};
			common.dialog({
				obj : "#modifyPoolDialog",
				url : baseURL + "/cluster/pool/modify",
				title : localeMsg.pool.modify,
				param : param,
				width : 600,
				heigth : 300,
				confirm : function() {
					var data = $("#modifyPoolForm").form('validate');
					if (data == true) {
						pool.modifysave();
					} else {
						common.showTip({
							title : localeMsg.common.warn,
							text : localeMsg.common.invalidData,
							success : false
						});
					}
				}
			});
		}
	},

	/**
	 * ModifySave pool
	 */
	modifysave : function() {
		$("#modifyPoolForm").ajaxSubmit({
			success : function(json) {
				if (json.result && json.result == "success") {
					common.showTip({
						title : localeMsg.common.info,
						text : localeMsg.common.saveSuccess,
						callback : function() {
							//pool.list();
							location.reload();
						},
						success : true
					});
				} else {
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.common.saveFailed,
						success : false
					});
				}
			}
		});
	},
	/**
	 * Remove pools
	 */
	remove : function() {
		// 用于选中复选框
		// push可以向数组的末位添加一个或多个元素并返回新的长度
		var poolName = this.value;
		/*var poolNames = [];
		$('input[name="poolName"]:checked').each(function() {
			poolNames.push($(this).val());
		});*/
		/*if (poolNames.length > 1) {
			common.showTip({
				title : localeMsg.common.warn,
				text : "不允许同时删除多项!"
			});
		} else {
			//var poolName = $("input[name='poolName']:checked").eq(0).val();
			var poolName = this.value;*/
			if(poolName == undefined){
				common.showTip({
					title : localeMsg.common.warn,
					text : localeMsg.common.selectMsg,
					success : false
				});
			}else{
				common.confirmDialog(localeMsg.common.relateddeleteconfirm,function() {
					pool.confirmRemove();
				});
			}
		//}
	},
	/**
	 * confirmRemove pools
	 */
	confirmRemove : function(){
		//var poolName = $("input[name='poolName']:checked").eq(0).val();
		//var poolName = this.value;
		String.prototype.trim = function()  
		{  
		return this.replace(/(^\s*)|(\s*$)/g, "");  
		}  
		var poolName = (this.value).trim();
		$.ajax({
			type : "post",
			url : baseURL + "/cluster/pool/remove",
			// 一个键值对
			data : {
				"poolName" : poolName
			},
			dataType : "json",
			// 删除数组
			traditional : true,
			success : function(json) {
				if(json.result=="2"){
					common.showTip({
						title : localeMsg.common.warn,
						text : localeMsg.pool.rbdLeft,
						success : false
					});
				}else{
					if (json.result && json.result == "success") {
						common.showTip({
							title : localeMsg.common.info,
							text : localeMsg.common.deleteSuccess,
							callback : function() {
								//pool.list();
								location.reload();
							},
							success: true
						});
					} else {
						common.showTip({
							title : localeMsg.common.warn,
							text : localeMsg.common.deleteFail,
							success: false
						});
					}
				}
			}
		});
	},
	/**
	 * validate form
	 */
	validate : function() {
		// poolName 验证非空，
		$('#poolName').validatebox({
			required : true,
			// 在页面取所有的name与传进来的value值比较
			validType : ['legalName', 'poolname'],
			validateOnCreate : false,	// 1.4.5版本支持
			validateOnBlur : true		// 1.4.5版本支持
		});
		// 失去焦点时验证是否唯一
		/*$('#poolName').checkAjax({
			url : baseURL + "/cluster/pool/validate",
			message : localeMsg.verification.repeat
		});*/
		// Pool Quota(GB)正数
		$('#quotaMax').validatebox({
			required : true,
			validType : 'positive_number'
		});
	},
	
	chartUsage: function(target, poolName) {
		var title = "";
		$.ajax({
			type : "get",
			url : baseURL + "/pool/display",
			data:{"poolName":poolName},
			dataType : "json",
			success : function(json) {
				if (!json || json.result != "success") { return; }
				var data = [];
				/*var pgs = json.data.numPgByStates;
				for (var i = 0; i < pgs.length; i++) {
					data.push({name: pgs[i].name, y: pgs[i].num});
				}*/
				var kbUsed = (json.data.kb_used);
				var used = (json.data.used);
				var maxAvail = json.data.max_avail;
				var max = json.data.max;
				var percent=((kbUsed*1024/maxAvail)*100).toFixed(2);
				 $(target).progressbar('setValue', percent);
				 $(target+"Avil").text(max);
				 $(target+"Used").text(used);
			}
		});
	},
	// 多个个实时指标计时器
	//timer_read: null, timer_write: null, timer_iops: null,
	Timer: new Array(),
	buildTimer : function(num){
		Timer=new Array(num);
		for(var i=0;i<num;i++)
			Timer[i]=null;
	},
	/**????
	 * 
	 */
	clearTimer : function(num) {
		clearInterval(pool.Timer[num]);
	},
	/**
	 * read pool
	 */
	read : function(target,num) {
		pool.clearTimer(num);
		/*var param = {}
		var isReal = $("input[name='isReal'][value='1']").is("input:checked");
		isReal = isReal == undefined ? true : isReal;
		var spanTime = $("#spanTime").val();
		if (spanTime) {
			param.spanTime = spanTime;
		}*/		
		var hrf="#"+target+"read";
		$.ajax({
			type : "get",
			url : baseURL + "/pool/chart_read?target="+target,
//			data : param,
			dataType : "json",
			success :function(json) {
				
			    $(hrf).highcharts({
			    	chart: {
			    		type: 'spline',
			    		height:280,
			            animation: Highcharts.svg, // don't animate in old IE
			            marginRight: 10,
			            events: {
			                load: function () {
			                    // set up the updating of the chart each 5 seconds
//			                	if (!isReal) return;
			                    var seriesArr = this.series;
			                    pool.Timer[num] = setInterval(function () {
			                    	$.ajax({
			                    		type : "get",
			                    		url : baseURL + "/pool/updated_read?target="+target,
			                    		dataType : "json",
			                    		beforeSend : function() {},
			                    		success :function(json) {
			                    			if (!json || json.dataset.length == 0) return;
			                    			var updateData = json.dataset;
			                    			var xNames = json.categories;
					                    	for (var i = 0; i < seriesArr.length; i++) {
					    	                    var series = seriesArr[i];
						                        var x = xNames[i];
						                        var yDatas = updateData[i].data;
					    	                    for (var j = 0; j < yDatas.length; j++) {
							                        var y = yDatas[j];
							                        series.addPoint([x,y],true,true);
					    	                    }
					                    	}
			                    		}
			                    		
			                    	});
			                    }, 10000);
			                }
			            }
			    	},
			        title: {
			            text:"",
			        },
			        xAxis: {//横坐标
			            categories: json.categories,
			            tickInterval: 120
			        },
			        yAxis: {//纵坐标
			            title: {
			                text: 'Bytes Per Second'
			            },
			            plotLines: [{
			                value: 0,
			                width: 1,
			                color: '#808080'
			            }]
			        },
			        legend:{
			        	enabled:false
			        },
			        series: json.dataset
			    });
			}
		});
	},
	
	/**
	 * read pool
	 */
	write : function(target,num) {
		pool.clearTimer(num);
		/*var param = {}
		var isReal = $("input[name='isReal'][value='1']").is("input:checked");
		isReal = isReal == undefined ? true : isReal;
		var spanTime = $("#spanTime").val();
		if (spanTime) {
			param.spanTime = spanTime;
		}*/		
		var hrf="#"+target+"write";
		$.ajax({
			type : "get",
			url : baseURL + "/pool/chart_write?target="+target,
//			data : param,
			dataType : "json",
			success :function(json) {
				
			    $(hrf).highcharts({
			    	chart: {
			    		type: 'spline',
			    		height:280,
			            animation: Highcharts.svg, // don't animate in old IE
			            marginRight: 10,
			            events: {
			                load: function () {
			                    // set up the updating of the chart each 5 seconds
//			                	if (!isReal) return;
			                    var seriesArr = this.series;
			                    pool.Timer[num] = setInterval(function () {
			                    	$.ajax({
			                    		type : "get",
			                    		url : baseURL + "/pool/updated_write?target="+target,
			                    		dataType : "json",
			                    		beforeSend : function() {},
			                    		success :function(json) {
			                    			if (!json || json.dataset.length == 0) return;
			                    			var updateData = json.dataset;
			                    			var xNames = json.categories;
					                    	for (var i = 0; i < seriesArr.length; i++) {
					    	                    var series = seriesArr[i];
						                        var x = xNames[i];
						                        var yDatas = updateData[i].data;
					    	                    for (var j = 0; j < yDatas.length; j++) {
							                        var y = yDatas[j];
							                        series.addPoint([x,y],true,true);
					    	                    }
					                    	}
			                    		}
			                    		
			                    	});
			                    }, 10000);
			                }
			            }
			    	},
			        title: {
			            text:"",
			        },
			        xAxis: {//横坐标
			            categories: json.categories,
			            tickInterval: 120
			        },
			        yAxis: {//纵坐标
			            title: {
			                text: 'Bytes Per Second'
			            },
			            plotLines: [{
			                value: 0,
			                width: 1,
			                color: '#808080'
			            }]
			        },
			        legend:{
			        	enabled:false
			        },
			        series: json.dataset
			    });
			}
		});
	},

	/**
	 * read pool
	 */
	operate : function(target,num) {
		pool.clearTimer(num);
		/*var param = {}
		var isReal = $("input[name='isReal'][value='1']").is("input:checked");
		isReal = isReal == undefined ? true : isReal;
		var spanTime = $("#spanTime").val();
		if (spanTime) {
			param.spanTime = spanTime;
		}*/		
		var hrf="#"+target+"operate";
		$.ajax({
			type : "get",
			url : baseURL + "/pool/chart_operate?target="+target,
//			data : param,
			dataType : "json",
			success :function(json) {
				
			    $(hrf).highcharts({
			    	chart: {
			    		type: 'spline',
			    		height:280,
			            animation: Highcharts.svg, // don't animate in old IE
			            marginRight: 10,
			            events: {
			                load: function () {
			                    // set up the updating of the chart each 5 seconds
//			                	if (!isReal) return;
			                    var seriesArr = this.series;
			                    pool.Timer[num] = setInterval(function () {
			                    	$.ajax({
			                    		type : "get",
			                    		url : baseURL + "/pool/updated_operate?target="+target,
			                    		dataType : "json",
			                    		beforeSend : function() {},
			                    		success :function(json) {
			                    			if (!json || json.dataset.length == 0) return;
			                    			var updateData = json.dataset;
			                    			var xNames = json.categories;
					                    	for (var i = 0; i < seriesArr.length; i++) {
					    	                    var series = seriesArr[i];
						                        var x = xNames[i];
						                        var yDatas = updateData[i].data;
					    	                    for (var j = 0; j < yDatas.length; j++) {
							                        var y = yDatas[j];
							                        series.addPoint([x,y],true,true);
					    	                    }
					                    	}
			                    		}
			                    		
			                    	});
			                    }, 10000);
			                }
			            }
			    	},
			        title: {
			            text:"",
			        },
			        xAxis: {//横坐标
			            categories: json.categories,
			            tickInterval: 120
			        },
			        yAxis: {//纵坐标
			            title: {
			                text: 'Bytes Per Second'
			            },
			            plotLines: [{
			                value: 0,
			                width: 1,
			                color: '#808080'
			            }]
			        },
			        legend:{
			        	enabled:false
			        },
			        series: json.dataset
			    });
			}
		});
	},


};
